package com.liu.project.controller;

import com.google.code.kaptcha.Producer;
import com.liu.project.config.KaptchaConfig;
import com.liu.project.pojo.Major;
import com.liu.project.pojo.UserInfo;
import com.liu.project.service.UserService;
import com.liu.project.service.VerifyService;
import com.liu.project.service.impl.AuthService;
import com.liu.project.utils.*;
import io.netty.handler.codec.base64.Base64Dialect;
import io.netty.handler.codec.base64.Base64Encoder;
import io.swagger.annotations.*;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: project
 * @description: 登录注册
 * @author: 86187
 * @create: 2022-01-11 15:29
 **/
@Api(tags = "用户验证",description = "用户登录成功、失败的返回实体；注册以及验证码发送")
@Controller
@RequestMapping("/api/auth")
public class AuthApiController {

    @Autowired
    UserService userService;
    @Autowired
    VerifyService verifyService;

//   http:fuwuqi /api/auth/login

    @Autowired
    private KaptchaConfig kaptchaConfig;

    @Autowired
    RedisUtil redisUtil;


    @Autowired
    AuthService authService;

    @GetMapping("/kaptcha")
    @ResponseBody
    public Message<Map<String ,Object>> getKaptcha(HttpServletResponse response) {

        response.setHeader("Cache-Control","no-store");
        response.setContentType("image/jpeg");
        Producer producer = kaptchaConfig.kaptchProducer();
        String text = producer.createText();
        String uuid = UUID.randomUUID().toString();
        System.out.println("uuid:"+uuid+",text:"+text);
        redisUtil.set("kaptcha:Code:"+uuid,text,60);//将验证码存入缓存
        //redisUtil.set("kaptcha:Code:"+uuid,text);//将验证码存入缓存
        BufferedImage image = producer.createImage(text);
       // ServletOutputStream outputStream=response.getOutputStream();
      //  ImageIO.write(image,"jpg",outputStream);
        //IOUtils.closeQuietly(outputStream);
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        Map<String,Object> map=new HashMap<>();
        try {
            ImageIO.write(image,"jpg",outputStream);
        } catch (IOException e) {
           return new Message(0,e.getMessage());
        }finally {
            map.put("UUid",uuid);
            map.put("img", new BASE64Encoder().encode(outputStream.toByteArray()));
            outputStream.close();

        }
        return new Message<Map<String,Object>>(200,"请求成功",map);
    }


    @GetMapping("/checkkaptchacode")
    @ResponseBody
     public Message checkKaCode(@RequestParam("kaptchaCode") String kaptchaCode,@RequestParam("uuid") String uuid){
        String o = (String) redisUtil.get("kaptcha:Code:" + uuid);//缓存取出的验证码
        if (!o.equals(kaptchaCode)){
            return new Message(0,"验证码错误");
        }
        return new Message(1,"验证码正确");
    }

    @PostMapping("/login")
   @ApiImplicitParams({@ApiImplicitParam(name = "username",value = "用户名",dataTypeClass = String.class),
                        @ApiImplicitParam(name = "password",value = "密码",dataType = "String")})
    public void login(String username,String password){
        System.out.println("登录接口");
    }


    //获取邮箱验换证
    @ApiOperation("获取验证码")
    @ApiImplicitParam(name = "username",value = "(账号)qq邮箱")
    @PostMapping("/verity-code")
    @ResponseBody
    public Message verityCode(@RequestParam("username") String username){
        try{
            verifyService.sendVerifyCode(username);
            System.out.println(username);
            return new Message(200,"邮件发送成功");
        }catch (Exception e){
            return new Message(500,"邮件发送异常");
        }

    }
//注册
    @ApiOperation(value = "用户注册")
    @GetMapping("/register")
    @ResponseBody
    public Message<Void>  register(@RequestParam("username") String username,
                            // @RequestParam("email") String email,
                            @RequestParam("password") String password,
                            @RequestParam("checkpwd")String checkpwd,
                            @RequestParam("verity") String verify){
        if (userService.findUserByUserName(username)==null){
            //用户名或者email已存在则注册失败
            if (!password.equals(checkpwd)){
                if (verifyService.doVerity(username,verify)){
                    UserInfo userInfo = new UserInfo();
                    userInfo.setEmail(username);
                    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                    String encode = bCryptPasswordEncoder.encode(password);
                    userService.addUser(username,encode,"USER", userInfo.getId());
                    return  new Message<>(200,"请求成功");
                }else  return new Message<>(0,"验证码错误，注册失败");
            }else return new Message<>(0,"两次密码不一致");

        }else return new Message<>(0,"用户已存在！");
    }

    //退出
    @GetMapping("/logout")
    public void logoutSuccess() {

    }

}
